#include "history.h"
#include "ui_history.h"

History::History(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);
    QObject::connect(this, SIGNAL(dataUpSignal(QByteArray)),
                     this, SLOT(dataUpSlot(QByteArray)));
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(SearchHistorySlot()));

    //    ui->dateTimeEdit->setCalendarPopup(true);
    //    ui->dateTimeEdit_2->setCalendarPopup(true);
    setupRealtimeDataDemo(ui->customPlot);
    ui->customPlot->replot();
    ui->checkBox_temp->setChecked(false);
    ui->checkBox_hum->setChecked(true);


}

History::~History()
{
    delete ui;
}

void History::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
    //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
    //#endif
    //demoName = "Real Time Data Demo";

    // include this section to fully disable antialiasing for higher performance:
    /*
     customPlot->setNotAntialiasedElements(QCP::aeAll);
     QFont font;
     font.setStyleStrategy(QFont::NoAntialias);
     customPlot->xAxis->setTickLabelFont(font);
     customPlot->yAxis->setTickLabelFont(font);
     customPlot->legend->setFont(font);
     */
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(Qt::blue));
    customPlot->graph(0)->setName("temp");
    //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
    //customPlot->graph(0)->setAntialiasedFill(false);
    customPlot->addGraph(); // red line
    customPlot->graph(1)->setPen(QPen(Qt::red));
    customPlot->graph(1)->setName("hum");
    //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("MM-dd hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(8);
//    customPlot->yAxis->setAutoTickStep(false);
    customPlot->yAxis->setTickStep(5);
//    customPlot->yAxis->setRange(10,40);
    customPlot->axisRect()->setupFullAxesBox();

    // make left and bottom axes transfer their ranges to right and top axes:
    //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
    customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);//可以进行鼠标位置 放大缩小 拖拽  放大缩小坐标系

}
//接收数据并显示
void History::dataUpSlot(QByteArray text)
{
    QString value(text);
    QJsonParseError parseJsonErr;
    QJsonDocument document = QJsonDocument::fromJson(value.toUtf8(),&parseJsonErr);
    QJsonObject jsonObject = document.object();
    qDebug()<<"type="<<jsonObject["type"].toInt();
    if(jsonObject["type"].toInt()==4)
    {
//        connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
//        dataTimer.start(1000); // Interval 0 means to refresh as fast as possible
        ui->customPlot->legend->setVisible(true);

        if(jsonObject.contains(QStringLiteral("result")))
        {
            QJsonValue jsonValueList = jsonObject.value(QStringLiteral("result"));
            QJsonObject item = jsonValueList.toObject();
            qDebug()<<"result="<<item["result"].toInt();
        }

        if(jsonObject.contains(QStringLiteral("data")))
        {
            QJsonValue arrayValue = jsonObject.value(QStringLiteral("data"));
            if(arrayValue.isArray())
            {
                QJsonArray array = arrayValue.toArray();
                for(int i=0;i<array.size();i++)
                {
                    QJsonValue iconArray = array.at(i);
                    QJsonObject icon = iconArray.toObject();
                    QString d =icon["time"].toString();
//                    int tim = icon["time"].toInt();
                    stime = d.toDouble();
                    QString t = icon["temp"].toString();
                    QString h = icon["hum"].toString();

                    qDebug()<<"time="<<stime<<"temp="<<t<<"hum="<<h;
//                    qDebug()<<"time1111111111111111="<<tim;
                    qDebug()<<"time22222222222222222222="<<d;

                    temp=t.toDouble();
                    hum=h.toDouble();
                    realtimeDataSlot();

                }
            }
        }
    }
    else
    {
        qDebug() << "type!=4";
    }
}

void History::SearchHistorySlot()
{
    QDateTime time = ui->dateTimeEdit->dateTime();
    uint startTime = time.toTime_t();

    time = ui->dateTimeEdit_2->dateTime();
    uint endTime = time.toTime_t();

    qDebug() << "startTime:" << startTime;
    qDebug() << "endddTime:" << endTime;

//    qDebug() << ui->comboBox->currentText();

    QMQTT::Message aaa;
    aaa.setTopic("down");
    QString s = "{\"type\": 4,\"data\":{\"key\":301,\"limit\": [%1,%2]}}\0";
    QString load=s.arg(startTime).arg(endTime);
    qDebug() << "load:" << load;
    aaa.setPayload(load.toUtf8());
    GlobalVal::mqtt->publish(aaa);

    //    {\"type\": 4,\"data\":{\"key\":301,\"limit\": [1666482618, 1666582621]}}
}

void History::realtimeDataSlot()
{
    //key的单位是秒
//    double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    double key = stime;
    qDebug() << "keyyyyyyyyyyyyy" <<  key;
//    qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
    //      double value0 = qrand() % 100;

//    if (ui->comboBox->currentText()=="温度")
//    {
//        ui->customPlot->graph(0)->addData(key, temp);//添加数据1到曲线1
//        ui->customPlot->graph(1)->setVisible(false);

//    }
//    else if (ui->comboBox->currentText()=="湿度")
//     {
//        ui->customPlot->graph(1)->addData(key, hum);//添加数据2到曲线2
//        ui->customPlot->graph(0)->setVisible(false);
//    }
    ui->customPlot->rescaleAxes();

    if (ui->checkBox_temp->isChecked())
    {

        ui->customPlot->graph(0)->addData(key, temp);//添加数据1到曲线1
         ui->customPlot->graph(0)->setVisible(true);
         ui->customPlot->rescaleAxes();

//        ui->customPlot->graph(1)->setVisible(false);
//        ui->checkBox_hum->setChecked(false);
    }
    if (ui->checkBox_hum->isChecked())
    {

        ui->customPlot->graph(1)->addData(key, hum);//添加数据2到曲线2
         ui->customPlot->graph(1)->setVisible(true);
//        ui->checkBox_temp->setChecked(false);
//        ui->customPlot->graph(0)->setVisible(false);
    }

    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
//    ui->customPlot->graph(0)->removeDataBefore(key-60);
//    ui->customPlot->graph(1)->removeDataBefore(key-60);

    //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
    //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
    ui->customPlot->graph(0)->rescaleValueAxis();
    ui->customPlot->graph(1)->rescaleValueAxis(true);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
    //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
    ui->customPlot->xAxis->setRange(key+0.25, 60, Qt::AlignRight);//设定x轴的范围
    ui->customPlot->xAxis->setTickLabelRotation(30);//设置刻度标签顺时针旋转10度
    ui->customPlot->replot();
}

void History::on_checkBox_hum_clicked()
{
    ui->checkBox_temp->setChecked(false);
    ui->customPlot->graph(0)->setVisible(false);
}

void History::on_checkBox_temp_clicked()
{
    ui->checkBox_hum->setChecked(false);
    ui->customPlot->graph(1)->setVisible(false);
}
